{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dea10fec",
   "metadata": {},
   "source": [
    "* 记录人：廖洪恩\n",
    "* 记录时间：2022年3月29日\n",
    "* 记录内容：图像识别\n",
    "* 参考文档：https://console.faceplusplus.com.cn/documents/4888391"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c2cd125e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.a817fce762a2e664fd5088bb11207194.315360000.1964936344.282335-25863392', 'expires_in': 2592000, 'session_key': '9mzdDoK43fQQbO8Wh+fLubnVM3Eo9MYdw1Zdf4nVZuVAapeP5t3oDx/1Y9Keuj8Rnvtow98mYoLHCDji8jUAXTY42VUI4w==', 'access_token': '24.504027fb9c50dc16d7a12a9444ea8bb6.2592000.1652168344.282335-25863392', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '71978e5c106e7a3606108bef4f32e41c'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload ={\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'GLTKUukmReM3i4KZFvrPSIdl',\n",
    "    'client_secret':'PwbscXSfn2LPqgxTGsO0wdnRZLzGe5dV'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9c79a3a8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.504027fb9c50dc16d7a12a9444ea8bb6.2592000.1652168344.282335-25863392'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Hongen_AI=response.json()['access_token']\n",
    "Hongen_AI"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f6473d1",
   "metadata": {},
   "source": [
    "* 请求参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1d6a38fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "d9853a69",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>参数</th>\n",
       "      <th>是否必选</th>\n",
       "      <th>类型</th>\n",
       "      <th>可选值范围</th>\n",
       "      <th>说明</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>image</td>\n",
       "      <td>和url二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>url</td>\n",
       "      <td>和image二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>baike_num</td>\n",
       "      <td>否</td>\n",
       "      <td>integer</td>\n",
       "      <td>-</td>\n",
       "      <td>返回百科信息的结果数，默认不返回</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          参数       是否必选       类型 可选值范围  \\\n",
       "0      image    和url二选一   string     -   \n",
       "1        url  和image二选一   string     -   \n",
       "2  baike_num          否  integer     -   \n",
       "\n",
       "                                                  说明  \n",
       "0  图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...  \n",
       "1  图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...  \n",
       "2                                   返回百科信息的结果数，默认不返回  "
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 图像识别URL\n",
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')[2]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ae84d64",
   "metadata": {},
   "source": [
    "## 示例代码\n",
    "encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"  \n",
    "二进制方式打开图片文件  \n",
    "f = open('[本地文件]', 'rb')  \n",
    "img = base64.b64encode(f.read())  \n",
    "\n",
    "params = {\"image\":img}  \n",
    "access_token = '[调用鉴权接口获取的token]'  \n",
    "request_url = request_url + \"?access_token=\" + access_token   \n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}  \n",
    "response = requests.post(request_url, data=params, headers=headers)  \n",
    "if response:  \n",
    "    print (response.json())  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "2070be46",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'calorie': '203', 'has_calorie': True, 'name': '特色羊排', 'probability': '0.961043', 'baike_info': {}}, {'calorie': '103', 'has_calorie': True, 'name': '羊腿', 'probability': '0.0346196', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%BE%8A%E8%85%BF/7046370', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/d833c895d143ad4be1c3c19c88025aafa50f06f8', 'description': '烤羊腿是呼伦贝尔招待宾客的一道佳肴名菜。烤羊腿是从烤全羊演变而来。经过长期的发展，在羊腿烘烤过程中逐步增加了各种配料和调味品，使其形、色、味、鲜集一体，色美、肉香、外焦、内嫩、干酥不腻，被人们赞为\"眼未见其物，香味已扑鼻\"。'}}, {'calorie': '172', 'has_calorie': True, 'name': '羊蝎子', 'probability': '0.00326948', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%BE%8A%E8%9D%8E%E5%AD%90/120911', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/8b13632762d0f703918fee59ceb0463d269758ee6fa9', 'description': '羊蝎子(Lamb Spine Hot Pot)，是一道鲁菜，主材是带里脊肉和脊髓的完整羊脊椎骨，因其形跟蝎子相似，故而俗称羊蝎子。羊蝎子常用来做清汤火锅，味道鲜美。羊蝎子经过长时间的焖，有利于促进钙的吸收，达到补钙的功效。故老年食之能缓解骨质疏松；中年食之，能养颜美容；少年食之，能健脑增高，并对患有慢性结肠炎、胃炎、气管炎等症状有明显的疗效。对工作、学习疲劳困倦，可起到加油充电的作用，堪称老少皆宜，四季均享的上乘美味佳肴。'}}, {'calorie': '197', 'has_calorie': True, 'name': '烤全羊', 'probability': '0.000481244', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%83%A4%E5%85%A8%E7%BE%8A/1203992', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/43a7d933c895d143ad4ba5c92dbb95025aafa50fa98c', 'description': '烤全羊(Roast Whole Lamb)，是一道地方特色菜肴。色、香、味、形俱全，别有风味。'}}, {'calorie': '125', 'has_calorie': True, 'name': '牛排', 'probability': '0.000152046', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%89%9B%E6%8E%92/1156436', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/a044ad345982b2b7d0a2b2eba9e2dcef76094b362dc6', 'description': '牛排，或称牛扒，是片状的牛肉，是西餐中常见的食物之一。牛排的烹调方法以煎和烤制为主。欧洲中世纪时，猪肉及羊肉是平民百姓的食用肉，牛肉则是王公贵族们的高级肉品，尊贵的牛肉被他们搭配上了当时也是享有尊贵身份的胡椒粉及香辛料一起烹调，并在特殊场合中供应，以彰显主人的尊贵身份。清末小说中已出现[牛排]、[猪排]等西菜菜名，可能是因形似上海[大排](猪丁骨)，故名[排]。而在上海方言里，[排]发[ba]音，广州话又作牛扒。'}}], 'log_id': 1513064028933423667}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "菜品识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('shipin.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "\n",
    "access_token = '24.504027fb9c50dc16d7a12a9444ea8bb6.2592000.1652168344.282335-25863392'\n",
    "payload={\n",
    "    'access_token':'24.504027fb9c50dc16d7a12a9444ea8bb6.2592000.1652168344.282335-25863392',\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "256002d0",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d1219ed",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
